package com.xtecher.app.column.ui;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.bartoszlipinski.recyclerviewheader2.RecyclerViewHeader;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xtecher.app.R;
import com.xtecher.app.base.BaseFragment;
import com.xtecher.app.column.ColumnContact;
import com.xtecher.app.column.ColumnPresenter;
import com.xtecher.app.column.adapter.BannerAdapter;
import com.xtecher.app.column.adapter.ColumnListAdapter;
import com.xtecher.app.column.bean.BannerResponse;
import com.xtecher.app.column.bean.ColumnListResponse;
import com.xtecher.app.column.bean.ColumnResponse;
import com.xtecher.app.utils.RecyclerUtils;
import com.xtecher.app.widget.OnItemClickListener;
import com.xtecher.app.widget.ZoomRecyclerView;
import com.xtecher.app.widget.clipview.ClipViewPager;
import com.xtecher.app.widget.clipview.ScalePageTransformer;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class ColumnFragment extends BaseFragment implements ColumnContact.View {


    ZoomRecyclerView reNews;
    ImageView imgTop;
    RecyclerViewHeader header;
    private RelativeLayout revBanner;
    private ClipViewPager vpBanner;
    private LinearLayout linPoint;

    private ColumnResponse column;
    private ColumnPresenter mPresenter;
    String url = "";
    private List<ColumnListResponse> columnListResponses;
    private ColumnListAdapter listAdapter;
    private View divider;
    private String lastId = "";
    private String startId = "";
    private BannerAdapter bannerAdapter;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 100:
                    if (vpBanner.getAdapter() == null) {
                        return;
                    }
                    int count = vpBanner.getAdapter().getCount();
                    /**
                     * 解决自动翻页 动画问题
                     */
                    if (count > 2) { // 实际上，多于1个，就多于3个
                        int position = vpBanner.getCurrentItem();
                        final int lastPosition = vpBanner.getAdapter().getCount() - 1;
                        if (position == 0) {
                            vpBanner.setCurrentItem(1, false);
                        } else if (position == lastPosition) {
                            vpBanner.setCurrentItem(2, false);
                        } else {
                            vpBanner.setCurrentItem(position + 1, true);
                        }
                        removeCallbacksAndMessages(null);
                        sendEmptyMessageDelayed(100, 3000);
                    }
                    break;
            }
        }
    };
    private SwipeRefreshLayout refreshLayout;
    private List<BannerResponse> valueBeen;
    private ImageView imgTopBack;
    private ImageView imgLoading;

    public static ColumnFragment newInstance(ColumnResponse res) {

        Bundle args = new Bundle();
        args.putParcelable("column", res);
        ColumnFragment fragment = new ColumnFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public ColumnFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        column = getArguments().getParcelable("column");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_recommend, container, false);
        initView(view);
        initListener();
        switch (String.valueOf(column.getId())) {
            case "1":
                startId = "0";
                mPresenter.getBanner();
                imgTop.setVisibility(View.GONE);
                revBanner.setVisibility(View.VISIBLE);
                refreshLayout.setEnabled(true);

                break;
            default:
                startId = "3000";
                revBanner.setVisibility(View.GONE);
                imgTop.setVisibility(View.VISIBLE);
                imgTopBack.setVisibility(View.VISIBLE);
                refreshLayout.setEnabled(false);
                reNews.setZoomView(imgTop);
                break;
        }

        url = String.format("?cid=%s&from=%s", column.getId(), startId);
        mPresenter.getColumnList(url);


        return view;
    }

    private void initListener() {
        reNews.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (RecyclerUtils.getScollYDistance(reNews) > -header.getHeight()) {
                    divider.setVisibility(View.VISIBLE);
                } else {
                    divider.setVisibility(View.GONE);
                }
                if (RecyclerUtils.isSlideToBottom(reNews) && !TextUtils.isEmpty(lastId)) {
                    loading = true;
                    url = String.format("?cid=%s&from=%s", column.getId(), lastId);
                    mPresenter.getColumnList(url);
                    lastId = "";
                }
            }
        });

        /**给ViewPager设置缩放动画，这里通过PageTransformer来实现**/
        vpBanner.setPageTransformer(true, new ScalePageTransformer());
        revBanner.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return vpBanner.dispatchTouchEvent(event);
            }
        });
        refreshLayout.setOnRefreshListener(() -> {
            isRefresh = true;
            startId = "0";
            mPresenter.getBanner();
            url = String.format("?cid=%s&from=%s", column.getId(), startId);
            mPresenter.getColumnList(url);
        });

        vpBanner.setOnItemFocusListener(new ClipViewPager.OnItemFocusListener() {
            @Override
            public void onitemFocus(int position) {
                Intent intent = new Intent(ColumnFragment.this.getContext(), ColumnDetailActivity.class);
                intent.putExtra("aid", Long.parseLong(valueBeen.get(vpBanner.getCurrentItem()).getAid()));
                ColumnFragment.this.startActivity(intent);
            }
        });

        reNews.setOnSlideUpListener(new ZoomRecyclerView.OnSlideUpListener() {
            @Override
            public void onSlideUp(View view) {
                if (0f != imgTop.getAlpha()) {
                    imgTop.setAlpha(0f);
                }
            }

            @Override
            public void onTop(View view) {
                if (1f != imgTop.getAlpha()) {
                    imgTop.setAlpha(1f);
                }
            }

            @Override
            public void onRefresh() {
                if (!isRefresh) {
                    imgLoading.setVisibility(View.VISIBLE);
                    isRefresh = true;
                    url = String.format("?cid=%s&from=%s", column.getId(), startId);
                    mPresenter.getColumnList(url);
                }
            }
        });


    }


    private void initView(View view) {
        isRefresh = true;
        refreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refreshLayout);
        reNews = (ZoomRecyclerView) view.findViewById(R.id.re_news);
        header = (RecyclerViewHeader) view.findViewById(R.id.header);
        imgTop = (ImageView) view.findViewById(R.id.img_top);
        imgLoading = (ImageView) view.findViewById(R.id.img_loading);
        imgTopBack = (ImageView) view.findViewById(R.id.img_top_back);
        divider = view.findViewById(R.id.view_divider);
        revBanner = (RelativeLayout) view.findViewById(R.id.rev_banner);
        vpBanner = (ClipViewPager) view.findViewById(R.id.vp_banner);
        linPoint = (LinearLayout) view.findViewById(R.id.lin_point);
        reNews.setLayoutManager(new LinearLayoutManager(getContext()));
        reNews.setItemAnimator(new DefaultItemAnimator());
        header.attachTo(reNews);

        mPresenter = new ColumnPresenter(this);
        columnListResponses = new ArrayList<>();
        listAdapter = new ColumnListAdapter(getContext(), columnListResponses);
        listAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view1, int position) {
                Intent intent = new Intent(ColumnFragment.this.getContext(), ColumnDetailActivity.class);
                intent.putExtra("aid", columnListResponses.get(position).getId());
                ColumnFragment.this.startActivity(intent);
            }
        });
        reNews.setAdapter(listAdapter);
        Glide.with(getContext())
                .load(column.getImage_2x())
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .placeholder(R.drawable.column_cover)
                .error(R.drawable.column_cover)
                .into(imgTop);
        Glide.with(getContext())
                .load(column.getImage_2x())
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .placeholder(R.drawable.column_cover)
                .error(R.drawable.column_cover)
                .into(imgTopBack);
        Glide.with(getContext())
                .load(R.drawable.loading)
                .into(imgLoading);

    }

    /**
     * 界面填充数据
     *
     * @param o
     * @param id
     */
    @Override
    public void setData(Object o, @Nullable int id) {
        switch (id) {
            case 0:
                if (columnListResponses != null && columnListResponses.size() == 0) {
                    isRefresh = true;
                }
                Type type = new TypeToken<List<ColumnListResponse>>() {
                }.getType();
                List<ColumnListResponse> responses = new Gson().fromJson(String.valueOf(o), type);
                if (responses != null && responses.size() > 0) {
                    if (isRefresh) {
                        columnListResponses.clear();
                        columnListResponses.addAll(responses);
                    }
                    if (loading) {
                        columnListResponses.addAll(responses);
                    }
                    listAdapter.notifyDataSetChanged();
                    lastId = String.valueOf(responses.get(responses.size() - 1).getId());
                }

                break;
            case 1:
                Type typeBn = new TypeToken<List<BannerResponse>>() {
                }.getType();
                List<BannerResponse> bannerResponses = new Gson().fromJson(String.valueOf(o), typeBn);
                if (bannerResponses == null || bannerResponses.size() == 0) {
                    revBanner.setVisibility(View.GONE);
                    imgTop.setVisibility(View.VISIBLE);
                }
                vpBanner.setOffscreenPageLimit(bannerResponses.size());
                initBanner(bannerResponses);
                break;
        }
    }

    private void initBanner(List<BannerResponse> valueBeen) {
        this.valueBeen = valueBeen;
        imgTop.setVisibility(View.GONE);
        revBanner.setVisibility(View.VISIBLE);
        int i = 0;
        while (i < valueBeen.size()) {
            linPoint.getChildAt(i).setVisibility(View.VISIBLE);
            i++;
        }
        linPoint.getChildAt(0).setBackgroundResource(R.drawable.sel_point);
        bannerAdapter = new BannerAdapter(getContext(), valueBeen);
        vpBanner.setAdapter(bannerAdapter);
        vpBanner.setCurrentItem(1, false);
        vpBanner.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < valueBeen.size(); i++) {
                    linPoint.getChildAt(i).setBackgroundResource(R.drawable.unsel_point);
                }
                if (position == 0) {
                    linPoint.getChildAt(valueBeen.size() - 1).setBackgroundResource(R.drawable.sel_point);
                } else if (position == valueBeen.size() + 1) {
                    linPoint.getChildAt(0).setBackgroundResource(R.drawable.sel_point);
                } else {
                    linPoint.getChildAt(position - 1).setBackgroundResource(R.drawable.sel_point);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (state == ViewPager.SCROLL_STATE_IDLE) {
                    handleSetCurrentItem(vpBanner.getCurrentItem());
                }
            }

            private void handleSetCurrentItem(int position) {
                final int lastPosition = vpBanner.getAdapter().getCount() - 1;
                if (position == 0) {
                    vpBanner.setCurrentItem(lastPosition == 0 ? 0 : lastPosition - 1, false);
                } else if (position == lastPosition) {
                    vpBanner.setCurrentItem(1, false);
                }
            }
        });

        vpBanner.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    handler.removeCallbacksAndMessages(null);
                    break;
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                    handler.sendEmptyMessageDelayed(100, 3000);
                    break;
            }
            return false;
        });
        handler.sendEmptyMessageDelayed(100, 3000);

    }

    @Override
    public void hideLoading() {
        super.hideLoading();
        if (isRefresh) {
            isRefresh = false;
            refreshLayout.setRefreshing(false);
            if (imgLoading.getVisibility() == View.VISIBLE){
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        imgLoading.setVisibility(View.GONE);
                    }
                },1000);
            }
        }
        if (loading) {
            loading = false;
        }
    }

    @Override
    public void showLoading(String msg) {
        if (isRefresh) {
            if (!refreshLayout.isEnabled()) {
                imgLoading.setVisibility(View.VISIBLE);
            }
        } else
            super.showLoading(msg);
    }
}
